package design.pattern.Lu15CompositePattern;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @program JavaBase
 * @description: 安全的组合模式
 *  部分-整体模式
 *  文件和文件夹、树形菜单
 * @author: zhanglu
 * @create: 2020-04-09 18:59:00
 */
public class CompositePattern01 {

    public static void main(String[] args) {

        Composite root = new Composite();

        Composite branch = new Composite();

        Leaf leaf = new Leaf();

        root.add(branch);
        root.add(leaf);

        branch.add(leaf);

        show(root);

    }

    public static void show(Composite composite){
        for (Component component : composite.getList()) {
            if(component instanceof Leaf){
                component.todo();
            }else {
                show((Composite) component);
            }
        }
    }

}

abstract class Component{
    public void todo(){
        System.out.println("抽象层做些通用的事情");
    }
}

class Leaf extends Component{

}

class Composite extends Component{

    private List<Component> componentList = new CopyOnWriteArrayList<>();

    public void add(Component component){
        this.componentList.add(component);
    }

    public void remove(Component component){
        this.componentList.remove(component);
    }

    public List<Component> getList(){
        return this.componentList;
    }

}


